import Vue from "vue";
import store from "@/store";
import Router from "vue-router";
import NProgress from "nprogress";
import { Message } from "element-ui";
import { load } from "@utils/utils";

Vue.use(Router);

var arr = [];

// 获取 view 下面那些 router
const r = require.context("../view/Login", true, /\.js$/);
r.keys().forEach((item) => {
  item = r(item);
  arr = arr.concat(item.default);
});

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/Home",
    redirect: "/Home/Demo",
    component: load("/Home/Home.vue"),
    children: [
      {
        path: "Demo",
        component: load("/Dovecote/Demo.vue"),
      },
      {
        path: "Demo2",
        component: load("/Dovecote/Demo2.vue"),
      },
      {
        path: "Demo3",
        component: load("/Dovecote/Demo3.vue"),
      },
    ],
  },
  ...arr,
  {
    path: "/Roots/RootsMange/:id",
    component: load("/Roots/RootsShow.vue"),
  },
];
// console.log('所有路由',routes);

const router = new Router({
  mode: "history",
  routes,
});

// 把路径还有名字放进Worktab 这个是标签导航栏用到的
const notoken = ["/login", "/register", "/forgetPassword"]; // 不需要tonken的页面

// 路由导航守卫
router.beforeEach((to, from, next) => {
  NProgress.start();

  // 扫码溯源页面放行，无需登录即可访问
  // /Roots/RootsMange/J20211123034001
  if (/^\/Roots\/RootsMange\/.*/.test(to.path)) {
    return next();
  }

  if (notoken.indexOf(to.path) == -1) {
    const token = sessionStorage.getItem("token");
    if (token == null || token == "") {
      Message.info("您不在登录状态，请先登录!");
      router.replace("/login");
    }
  }
  let name = to.path.split("/");
  // console.log('去到',name)
  store.dispatch("worktabRoute", {
    to: {
      name: to.meta.title,
      path: to.fullPath,
    },
    from: {
      name: from.meta.title,
      path: from.fullPath,
    },
  });
  if (name[name.length - 1] === "VisualPlatform") {
    //这个模块没做，暂时拦截掉
    return;
  }
  next();
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
